package zl.ordermanager.controller;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import jxl.Sheet;
import jxl.Workbook;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import zl.ordermanager.service.SalesOrderService;
import zl.ordermanager.service.UserService;
import zl.ordermanager.vo.DataGrid;
import zl.ordermanager.vo.PageHelper;
import zl.ordermanager.vo.SalesOrder;

@Controller
@RequestMapping("/salesOrder")
public class SalesOrderController extends BaseController {

	@Autowired
	private SalesOrderService salesOrderService;

	@Autowired
	private UserService userService;

	@RequestMapping("/showList")
	public String showList(PageHelper pageHelper, Model model) {
		DataGrid<SalesOrder> dataGrid = salesOrderService.dataGrid(pageHelper);
		List<SalesOrder> salesOrderList = dataGrid.getList();
		long totalCount = dataGrid.getTotal();

		model.addAttribute("salesOrderList", salesOrderList);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageHelper", pageHelper);

		return "salesOrderList";
	}

	@RequestMapping("/showAdd")
	public String showAdd(Model model) {
		return "salesOrderAdd";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ModelAndView add(SalesOrder salesOrder) {
		try {
			salesOrderService.add(salesOrder);
		} catch (Exception e) {
			return ajaxDoneError(e.getMessage());
		}

		return ajaxDoneSuccess("操作成功");
	}

	@RequestMapping("/showEdit/{orderId}")
	public String showEdit(@PathVariable("orderId") Integer orderId, Model model) {
		SalesOrder salesOrder = salesOrderService.get(orderId);

		model.addAttribute("salesOrder", salesOrder);

		return "salesOrderEdit";
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public ModelAndView edit(SalesOrder salesOrder) {
		try {
			salesOrderService.edit(salesOrder);
		} catch (Exception e) {
			return ajaxDoneError(e.getMessage());
		}
		return ajaxDoneSuccess("操作成功");
	}

	@RequestMapping("/delete/{orderId}")
	public ModelAndView delete(@PathVariable("orderId") Integer orderId) {

		salesOrderService.delete(orderId);

		return ajaxDoneSuccess("操作成功");
	}

	@RequestMapping("/upload")
	public ModelAndView upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request) {

		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();
		// String fileName = new Date().getTime()+".jpg";
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}

		// 保存
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			return ajaxDoneError(e.getMessage());
		}

		try {
			importExcel(targetFile);
		} catch (Exception e) {
			return ajaxDoneError(e.getMessage());
		} finally {
			targetFile.delete();
		}

		return ajaxDoneSuccess("导入成功");
	}

	private void importExcel(File file) throws Exception {
		if (!file.getName().substring(file.getName().length() - 3).equals("xls")) {
			throw new Exception("文件不是Excel文件！");
		}

		Workbook workbook = Workbook.getWorkbook(file);
		Sheet sheet = workbook.getSheet(0);
		if ((sheet.getCell(0, 0).getContents().equals("单据编号") || sheet.getCell(0, 0).getContents().equals("订单号"))
				&& (sheet.getCell(1, 0).getContents().equals("日期") || sheet.getCell(1, 0).getContents().equals("时间"))
				&& (sheet.getCell(2, 0).getContents().equals("单位全名") || sheet.getCell(2, 0).getContents()
						.equals("客户名称"))
				&& (sheet.getCell(3, 0).getContents().equals("经手人全名") || sheet.getCell(3, 0).getContents()
						.equals("业务员"))) {
			int row = 1;
			while (row < sheet.getRows()) {
				String orderNo = sheet.getCell(0, row).getContents();
				String orderDate = sheet.getCell(1, row).getContents();
				String customer = sheet.getCell(2, row).getContents();
				String salesman = sheet.getCell(3, row).getContents();
				String money = sheet.getCell(4, row).getContents();

				if (orderNo == null || orderNo.isEmpty()) {
					continue;
				}
				SalesOrder findSalesOrder = salesOrderService.getByOrderNo(orderNo);
				if (findSalesOrder == null) {
					SalesOrder salesOrder = new SalesOrder();
					salesOrder.setOrderNo(orderNo);
					salesOrder.setOrderDate(orderDate);
					salesOrder.setCustomer(customer);
					salesOrder.setSalesman(salesman);
					salesOrder.setMoney(money);

					salesOrderService.add(salesOrder);
				} else {
					findSalesOrder.setOrderDate(orderDate);
					findSalesOrder.setCustomer(customer);
					findSalesOrder.setSalesman(salesman);
					findSalesOrder.setMoney(money);

					salesOrderService.edit(findSalesOrder);
				}

				row++;
			}
		} else {
			throw new Exception("Excel文件格式错误");
		}
	}
}
